package saleMarket.controller.basic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import saleMarket.domain.FreightCargo;
import saleMarket.service.FreightCargoService;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

@Slf4j
@WebServlet("/freightCargo.ctl")
public class FreightCargoController extends HttpServlet {
    /**
     * GET, http://localhost:8080/freightCargo.ctl?id=1, 查询id=1的项目
     * GET, http://localhost:8080/freightCargo.ctl, 查询所有的项目
     * 把一个或所有类别对象响应到前端
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //读取参数id
        String id_str = request.getParameter("id");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();

        try {
            //如果id_str != null, 说明请求数据有id键，是请求某个对象
            if (id_str != null) {
                int id = Integer.parseInt(id_str);
                responseFreightCargo(id, response);
            } else {
                //响应多个信息，其中conditionList, pagination两个对象引用为空是可能的
                this.responseFreightCargos(response);
            }
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            log.debug(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试
            log.debug(e.getMessage());
        }
    }

    //按分页信息响应符合条件的对象和对象总数
    private void responseFreightCargos(HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //分页获得满足条件的所有对象
        Collection<FreightCargo> freightCargos=
                FreightCargoService.getInstance().findAll();
        //第二个参数可以防止循环引用
        String freightCargo_jsonStr = JSON.toJSONString(freightCargos,
                SerializerFeature.DisableCircularReferenceDetect);
        //响应resp_jsonObj到前端0
        response.getWriter().println(freightCargo_jsonStr);

    }
    //响应一个对象
    private void responseFreightCargo(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        Collection<FreightCargo> freightCargos=new ArrayList<>();
        //根据id查找
        FreightCargo freightCargo =
                FreightCargoService.getInstance().find(id);
        freightCargos.add(freightCargo);
        String freightCargo_jsonStr = JSON.toJSONString(freightCargos,
                SerializerFeature.DisableCircularReferenceDetect);
        //响应到前端
        response.getWriter().println(freightCargo_jsonStr);
    }

    /**
     * POST, http://localhost:8080/freightCargo.ctl, 增加项目
     * 增加一个项目对象：将来自前端请求的JSON对象，增加到数据库表中
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String GP_json = JSONUtil.getJSON(request);
        JSONObject req_jsonObj = JSON.parseObject(GP_json);
        //将JSON字串解析为对象
        FreightCargo freightCargoToAdd =
                JSON.parseObject(GP_json,FreightCargo.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //在数据库表中增加对象
        try {
                FreightCargoService.getInstance().add(freightCargoToAdd);
                message.put("message", "增加成功");
                log.debug("增加成功");
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            log.debug(e.getMessage());
        }catch(Exception e){
            message.put("message", "网络异常");
            log.debug(e.getMessage());
        }
        //响应message到前端
        response.getWriter().println(message);
    }

    /**
     * DELETE, http://localhost:8080/freightCargo.ctl?id=2, 删除id=2的项目
     * 删除一个项目对象：根据来自前端请求的id，删除数据库表中id的对应记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //读取参数id
        String id_str = request.getParameter("id");
        int id = Integer.parseInt(id_str);
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的项目
            FreightCargoService.getInstance().delete(id);
            respMessage_jsonObj.put("message", "删除成功");
            log.debug("删除成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试
            log.debug(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试
            log.debug(e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }
    /**
     * PUT, http://localhost:8080/freightCargo.ctl, 修改项目
     *
     * 修改一个项目对象：将来自前端请求的JSON对象，更新数据库表中相同id的记录
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String request_json= JSONUtil.getJSON(request);
        //将JSON字串解析为对象
        FreightCargo FreightCargoToUpdate = JSON.parseObject(request_json, FreightCargo.class);
        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        //到数据库表修改对象对应的记录
        try {if (FreightCargoToUpdate!=null) {
            FreightCargoService.getInstance().update(FreightCargoToUpdate);
            message.put("message", "修改成功");
            log.debug("修改成功");
        }
        }catch (SQLException e){
            message.put("message", "数据库操作异常");
            e.printStackTrace();
        }catch(Exception e){
            message.put("message", "网络异常");
            log.debug(e.getMessage());
        }
        //响应message到前端
        response.getWriter().println(message);
    }
}
